package com.autoplaza;

import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

//import kankan.wheel.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MiGarage extends Activity {
	String[] foto, marca, modelo, version, year, precio, kilometraje, estado, transmision, color, numfoto,
	colorint, financiamiento, vestiduras, anuncio;
	int contador=0, tam, var=0;
	private ProgressDialog progressDialog;
	ListView list;
	Resultados_Adapter adapter;
	Timer tim;
	String comparative;

	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.migarage);
        
        if(checkData() == true){
    		new AsyncActividades().execute("actividades");
        }else{
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("No tiene autos agregados a su Garage. Puede " +
					"agregar autos desde la pantalla de detalle de cada anuncio")
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   Intent back = new Intent(MiGarage.this, Buscar.class);
			        	   startActivity(back);
			           }
			       });
			AlertDialog alertDialog = builder.create();
			alertDialog.setTitle("Autoplaza");
			alertDialog.show();
        }
        
    }
	
	@Override
	public void onBackPressed() {
		Intent back = new Intent(MiGarage.this, Buscar.class);
		startActivity(back);
	}
	
    public boolean isNetwork(){
    	boolean bool = false;
    	HttpGet requestForTest = new HttpGet("http://m.google.com");
        try {
            new DefaultHttpClient().execute(requestForTest); // can last...
            bool = true;
        } catch (Exception e) {}
		return bool;
    }
    
	private void dialogoInternet() {
		AlertDialog.Builder builder = new AlertDialog.Builder(MiGarage.this);
		builder.setMessage("Necesita conexión a Internet")
		       .setCancelable(false)
		       .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		           }
		       });
		AlertDialog alertDialog = builder.create();
		alertDialog.show();		
								
	}
	
	private class AsyncActividades extends AsyncTask<String, Void, Integer> {
		
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(MiGarage.this, "",
					"Buscando...");	
		}
		protected Integer doInBackground(String... urls) {
			//Calculo de los arreglos en segundo plano
        	GetArrays();
			return null;
		}
		protected void onPostExecute(Integer in) {
				list = (ListView) findViewById(R.id.list);
				adapter=new Resultados_Adapter(MiGarage.this, marca, modelo, year, version, transmision, kilometraje, precio, estado, foto, numfoto,anuncio, null, null, null);
				list.setAdapter(adapter);
				list.setTextFilterEnabled(true);
				tim=new Timer();
				tim.schedule(new TimerTask() {
					@Override
					public void run() {
						MiGarage.this.runOnUiThread(new Runnable() {
						    public void run() {
								adapter.notifyDataSetChanged();
						    }
						});
					}
				}, 0, 2000);
				
				list.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent, View view,
							final int position, long id) {
						
						final Dialog dialog = new Dialog(MiGarage.this);
						dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
						dialog.setContentView(R.layout.garagedialog);
						dialog.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
						
						
						final Button comparativo = (Button) dialog.findViewById(R.id.btcomparativo);
						
						comparative = checkComparative(anuncio[position]);
						
						if(comparative.equals("si")){
							comparativo.setText("Remover de Comparativo");
						}else if(comparative.equals("no")){
							comparativo.setText("Agregar de Comparativo");
						}
						
						comparativo.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								comparative = checkComparative(anuncio[position]);

								if(comparative.equals("si")){
									comparativo.setText("Agregar a Comparativo");
									//Abrimos la base de datos 'DBUsuarios' en modo escritura
							        SQLiteHelper usdbh = new SQLiteHelper(getApplicationContext(), "DBGarage", null, 1);
							        SQLiteDatabase db = usdbh.getWritableDatabase();
							        //Si hemos abierto correctamente la base de datos
							        if(db != null)
							        {
							        	db.execSQL("UPDATE Garage SET comparativo='no' WHERE anuncio='"+anuncio[position]+"' ");
//							            //Insertamos los datos en la tabla Usuarios
//							            db.execSQL("INSERT INTO Garage (comparativo) " +
//							                           "VALUES ('" + 0 +"') WHERE anuncio='"+anuncio[position]+"'");
							            //Cerramos la base de datos
							            db.close();
							        }
									
								}else if (comparative.equals("no")){
									comparativo.setText("Remover de Comparativo");
									//Abrimos la base de datos 'DBUsuarios' en modo escritura
							        SQLiteHelper usdbh = new SQLiteHelper(getApplicationContext(), "DBGarage", null, 1);
							        SQLiteDatabase db = usdbh.getWritableDatabase();
							        //Si hemos abierto correctamente la base de datos
							        if(db != null)
							        {
							        	db.execSQL("UPDATE Garage SET comparativo='si' WHERE anuncio='"+anuncio[position]+"' ");

							            //Cerramos la base de datos
							            db.close();
							        }
									
								}

							}
						});
						
						Button detail = (Button) dialog.findViewById(R.id.btdetalle);
						detail.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								dialog.dismiss();
								if(isNetwork()==true){
									Intent in = new Intent(MiGarage.this, DetalleaUTO.class);
									in.putExtra("modelo",""+modelo[position]);
									in.putExtra("numanuncio",""+anuncio[position]);
									in.putExtra("precio",""+precio[position]);
									in.putExtra("foto",""+foto[position]);
									in.putExtra("numfoto",""+numfoto[position]);
									in.putExtra("version",""+version[position]);
									in.putExtra("migarage", "1");
									startActivity(in);
								}else{
									dialogoInternet();
									
								}								
							}
						});
						
						Button galery = (Button) dialog.findViewById(R.id.btfotos);
						galery.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View arg0) {
								dialog.dismiss();
								if(isNetwork()){
									Intent gallery=new Intent(MiGarage.this, Galeria.class);
									gallery.putExtra("idanuncio", anuncio[position]);
									gallery.putExtra("marca", ""+marca[position]);
									gallery.putExtra("modelo", ""+modelo[position]);
									gallery.putExtra("year", ""+year[position]);
									startActivity(gallery);
								}else{
									dialogoInternet();
								}
							}
						});
						
						Button cancel = (Button) dialog.findViewById(R.id.btcancel);
						cancel.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								dialog.dismiss();
							}
						});
						
						Button eliminar = (Button) dialog.findViewById(R.id.bteliminar);
						eliminar.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog.dismiss();
								deleteMethod(position);
								

							}


						});
						
						dialog.show();
						
						
					}
				});
				
				progressDialog.dismiss();
			}
	}
	
	
	
	
	

	
	private void deleteMethod(int pos) {
		//Abrimos la base de datos 'DBUsuarios' en modo escritura
        SQLiteHelper usdbh = new SQLiteHelper(getApplicationContext(), "DBGarage", null, 1);
        SQLiteDatabase db = usdbh.getWritableDatabase();
		
        //Si hemos abierto correctamente la base de datos
        if(db != null)
        {
			//Eliminar un registro
			db.execSQL("DELETE FROM Garage WHERE anuncio='"+anuncio[pos]+"' ");
			
            //Cerramos la base de datos
            db.close();
        }
		Toast.makeText(getApplicationContext(), "Auto eliminado de Mi Garage exitosamente", Toast.LENGTH_LONG).show();
		Intent reload = new Intent(MiGarage.this, MiGarage.class);
		startActivity(reload);
		//		new AsyncActividades().execute("actividades");								
	}
    
    
	 private void GetArrays() {
		 SQLiteHelper usdbh = new SQLiteHelper(getApplicationContext(), "DBGarage", null, 1);
	        SQLiteDatabase db = usdbh.getWritableDatabase();
	        if(db != null)
	        {
	        	Cursor c = db.rawQuery(" SELECT * FROM Garage", null);
	        	tam = c.getCount();
	        	
	        	foto = new String[tam];
	        	marca = new String[tam];
	        	modelo = new String[tam];
	        	version = new String[tam];
	        	year = new String[tam];
	        	precio = new String[tam];
	        	kilometraje = new String[tam];
	        	estado = new String[tam];
	        	transmision = new String[tam];
	        	color = new String[tam];
	        	colorint = new String[tam];
	        	financiamiento = new String[tam];
	        	vestiduras = new String[tam];
	        	anuncio = new String[tam];
	        	numfoto = new String[tam];
	        	
	        	//Nos aseguramos de que existe al menos un registro
	        	if (c.moveToFirst()) {
	        	     //Recorremos el cursor hasta que no haya más registros
	        	     do {
	        	    	  foto[contador] = c.getString(0);
	        	    	  marca[contador] = c.getString(1);
	        	    	  modelo[contador] = c.getString(2);
	        	    	  version[contador] = c.getString(3);
	        	    	  year[contador] = c.getString(4);
	        	    	  precio[contador] = c.getString(5);
	        	    	  kilometraje[contador] = c.getString(6);
	        	    	  estado[contador] = c.getString(7);
	        	    	  transmision[contador] = c.getString(8);
	        	    	  color[contador] = c.getString(9);
	        	    	  colorint[contador] = c.getString(10);
	        	    	  financiamiento[contador] = c.getString(11);
	        	    	  vestiduras[contador] = c.getString(12);
	        	    	  anuncio[contador] = c.getString(13);
	        	    	  numfoto[contador] = c.getString(14);
	        	    	  contador++;
	        	     } while(c.moveToNext());
	        	}
	        	db.close();
	        }else{
	        	
	        	
	        }
	}

	/*checar este metodo*/
	protected String checkComparative(String anuncio) {
		 	String comparative = null;
		 	
			//Abrimos la base de datos 'DBUsuarios' en modo escritura
	        SQLiteHelper usdbh = new SQLiteHelper(getApplicationContext(), "DBGarage", null, 1);
	        SQLiteDatabase db = usdbh.getWritableDatabase();
	        
	        if(db != null)
	        {
	        	   Cursor c = db.rawQuery("SELECT comparativo FROM Garage WHERE anuncio='"+anuncio+"'", null);
	     	      //Nos aseguramos de que existe al menos un registro
	     	        if (c.moveToFirst()) {
	     	        	Log.i("Existe registro", "comparative "+c.getString(0));
	     	        	
	     	        	comparative = c.getString(0);
//	     	        }else{
//	     	        	Log.i("No Existe registro", "TRUE");
//	     	        	bool = false;
	     	        }
	     	        db.close();	
	        }
	     
	        return comparative;
	}

	protected boolean checkData() {
		 	boolean bool = false;
			//Abrimos la base de datos 'DBUsuarios' en modo escritura
	        SQLiteHelper usdbh = new SQLiteHelper(getApplicationContext(), "DBGarage", null, 1);
	        SQLiteDatabase db = usdbh.getWritableDatabase();
	        
	        if(db != null)
	        {
	        	   Cursor c = db.rawQuery(" SELECT * FROM Garage", null);
	     	      //Nos aseguramos de que existe al menos un registro
	     	        if (c.moveToFirst()) {
	     	        	bool = true;
	     	        }else{
	     	        	bool = false;
	     	        }
	     	        db.close();	
	        }
	     
	        return bool;
	}
    
//	public boolean onCreateOptionsMenu(Menu menu) {
//	    super.onCreateOptionsMenu(menu);
//	    MenuInflater inflater = getMenuInflater();
//	    inflater.inflate(R.menu.menuprin, menu);
//	    return true;
//	}
//	
//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		switch(item.getItemId()){
//		case R.id.buscar:
//			Intent buscar  = new Intent(MiGarage.this, Buscar.class);
//			startActivity(buscar);
//			break;
//		case R.id.noticias:
//			Intent noticias  = new Intent(MiGarage.this, Noticias.class);
//			startActivity(noticias);
//			break;
//		case R.id.mas:
//			Intent mas  = new Intent(MiGarage.this, Mas.class);
//			startActivity(mas);
//			break;
//		}
//		return super.onOptionsItemSelected(item);
//	}

}